package com.tools.core;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.apache.commons.lang3.StringUtils;

public class InitHtml {
	/**
	 * 解析注解，返回查询的HTML
	 * 
	 * @param method
	 * @param field
	 * @param entitySet
	 * @return
	 */
	public StringBuffer initQuery(Class clazz, Method method, Field field,
			EntitySet entitySet) {
		if (entitySet != null) {
			if (!StringUtils.isEmpty(entitySet.queryBy())) {

				String name = null == method ? field.getName() : method
						.getName();
				StringBuffer html = new StringBuffer();
				String globStr = "                    ";
				String globStr1 = "            ";
				html.append(globStr + "&nbsp;&nbsp;&nbsp;" + entitySet.name()
						+ "&nbsp;\n");
				html.append(initDom(clazz, name, entitySet, globStr1, true));
				html.append(globStr + "&nbsp;&nbsp;\n");
				return html;
			}
		}
		return new StringBuffer("");
	}

	/**
	 * 解析注解，返回JS查询代码
	 * 
	 * @param method
	 * @param field
	 * @param entitySet
	 * @return
	 */
	public StringBuffer initQueryJs(Class clazz, Method method, Field field,
			EntitySet entitySet) {
		if (entitySet != null) {
			if (!StringUtils.isEmpty(entitySet.queryBy())) {
				String columnName = "";
				if (null != method) {
					columnName = method.getName();
					columnName = columnName.substring(3, 4).toLowerCase()
							+ columnName.substring(4);
				}
				if (null != field) {
					columnName = field.getName();
				}
				StringBuffer js = new StringBuffer();
				String globStr = "            ";
				js.append("\n");
				js.append(globStr + "//" + entitySet.name() + "\n");
				js.append(globStr);
				if (entitySet.inputType().equals("text".trim())) {
					js.append("'query." + columnName + "&"
							+ entitySet.queryBy().trim() + "':" + "$('#"
							+ columnName + "').val()");
				} else if (entitySet.inputType().equals("select".trim())) {
					if (entitySet.css().equals("combobox")
							|| entitySet.css().equals("validatebox")) {
						js.append("'query." + columnName + "&"
								+ entitySet.queryBy().trim() + "':" + "$('#"
								+ columnName + "').combobox('getValue')");
					} else if (entitySet.css().equals("combotree")) {
						js.append("'query." + "." + columnName + "&"
								+ entitySet.queryBy().trim() + "':" + "$('#"
								+ columnName
								+ "').combotree('tree').tree('getSelected')");
					}
				}
				return js;
			}
		}
		return new StringBuffer("");
	}

	/**
	 * 生成List页面中的字段HTML
	 * 
	 * @param method
	 * @param field
	 * @param entitySet
	 * @return
	 */
	public StringBuffer initList(Method method, Field field, EntitySet entitySet) {
		String align = "center";
		String columnName = "";
		String type = "";
		if (null != method) {
			type = method.getReturnType().getSimpleName();
			columnName = method.getName();
			columnName = columnName.substring(3, 4).toLowerCase()
					+ columnName.substring(4);
		}
		if (null != field) {
			type = field.getType().getSimpleName();
			columnName = field.getName();
		}
		if (type.toLowerCase().indexOf("int") >= 0
				|| type.toLowerCase().indexOf("date") >= 0) {
			align = "right";
		}
		StringBuffer html = new StringBuffer();
		String globeStr = "                    ";
		html.append(globeStr + "<th data-options=\"field:'" + columnName
				+ "',width:80,title:'" + entitySet.name() + "',align:'" + align
				+ "',sortable:'true'\"");
		if ("textarea".equals(entitySet.inputType())) {
			html.append(" formatter=\"formatterStr\"");
		}
		html.append("></th>\n");
		return html;
	}

	/**
	 * 根据注解生成编辑页面的字段HTML
	 * 
	 * @param clazz
	 *            使用注解的类
	 * @param name
	 *            字段名称
	 * @param entitySet
	 *            注解实体，用来取值
	 * @return
	 */
	public StringBuffer initEdit(Class clazz, String name, EntitySet entitySet) {
		String globStr = "                ";
		StringBuffer html = new StringBuffer(globStr + "<tr>\n");
		html.append(globStr + "<td align='right'>" + entitySet.name()
				+ "</td>\n");
		html.append(globStr + "    <td>\n");
		String clzName = clazz.getSimpleName().substring(0, 1).toLowerCase()
				+ clazz.getSimpleName().substring(1);
		// 当前字段名称
		if (name.indexOf("get") == 0) {
			name = name.substring(3, 4).toLowerCase() + name.substring(4);
		}
		while (!ParseEntitySet.isInsertId) {
			html.append(globStr + "        <input type='hidden' name='"
					+ clzName + ".id' id='id' value=\"${" + clzName
					+ ".id}\"/>\n");
			ParseEntitySet.isInsertId = !ParseEntitySet.isInsertId;
		}
		html.append(initDom(clazz, name, entitySet, globStr, false));
		html.append(globStr + "    </td>\n");
		html.append(globStr + "</tr>\n");
		return html;
	}

	public StringBuffer initDetail(Class clazz, String name, EntitySet entitySet) {
		String globStr = "                ";
		StringBuffer html = new StringBuffer(globStr + "<tr>\n");
		html.append(globStr + "<th align='right'>" + entitySet.name()
				+ "</th>\n");
		html.append(globStr + "    <td>\n");
		String clzName = clazz.getSimpleName().substring(0, 1).toLowerCase()
				+ clazz.getSimpleName().substring(1);
		// 当前字段名称
		if (name.indexOf("get") == 0) {
			name = name.substring(3, 4).toLowerCase() + name.substring(4);
		}
		if ("select".equals(entitySet.inputType())) {
			for (int i = 0; i < entitySet.vals().length; i++) {
				String str = entitySet.vals()[i];
				html.append(globStr + "    <c:if test=\"${" + clzName + "."
						+ name + " eq ");
				try {
					html.append(Integer.parseInt(str));
				} catch (Exception e) {
					html.append("\'" + str + "\'");
				}
				html.append("}\">" + entitySet.keys()[i] + "</c:if>\n");
				// html.append(globStr +
				// "    <c:if test=\"${"+clzName+"."+name+" eq "+str+"}\">"+str+"</c:if>\n");
			}
		} else {
			html.append(globStr + "    ${" + clzName + "." + name + "}\n");
		}
		html.append(globStr + "    </td>\n");
		html.append(globStr + "</tr>\n");
		return html;
	}

	/**
	 * 根据注解，初始化一个dom元素
	 * 
	 * @param clazz
	 *            类
	 * @param name
	 *            字段名称
	 * @param entitySet
	 *            注解
	 * @param globStr
	 *            该字符串用来调整页面格式，一般为多个
	 * @param isquery
	 *            是否为查询时创建的dom
	 * @return
	 */
	public StringBuffer initDom(Class clazz, String name, EntitySet entitySet,
			String globStr, boolean isquery) {
		StringBuffer html = new StringBuffer();
		String type = entitySet.inputType();
		String clzName = clazz.getSimpleName().substring(0, 1).toLowerCase()
				+ clazz.getSimpleName().substring(1);
		String width = isquery ? "width:100px" : "width:80%";
		if ("select".equals(type)) {
			String css = "";
			if ("validatebox".equals(entitySet.css())
					|| StringUtils.isEmpty(entitySet.css())) {
				css = "combobox";
			} else {
				css = entitySet.css();
			}
			if (!StringUtils.isEmpty(entitySet.selUrl())) {
				html.append(globStr + "        <select style=\"" + width
						+ "\" name='" + clzName + "." + name + "' id='" + name
						+ "' class='easyui-" + css + "' data-options=\"");
				StringBuffer opt = new StringBuffer();
				if (entitySet.selOpts().length == entitySet.selVals().length) {
					for (int i = 0; i < entitySet.selOpts().length; i++) {
						String key = entitySet.selOpts()[i];
						String value = entitySet.selVals()[i];
						if (isquery && "required".equals(key.trim()))
							continue;
						if (isquery && "missingMessage".equals(key.trim()))
							continue;
						if (isquery && "invalidMessage".equals(key.trim()))
							continue;
						if (isquery && "validType".equals(key.trim()))
							continue;
						if (!StringUtils.isEmpty(opt.toString()))
							opt.append(",");
						opt.append(key + ":\'" + value + "\'");
					}
					html.append(opt);
				}
				html.append(",url:'<c:url value='" + entitySet.selUrl()
						+ "'/>'\" >");
				html.append("</select>\n");
			} else {
				html.append(globStr + "        <select style=\"" + width
						+ "\" class='easyui-" + css + "' name='" + clzName
						+ "." + name + "' id='" + name + "' data-options=\"");
				// easyui的参数
				StringBuffer opt = new StringBuffer();
				if (entitySet.selOpts().length == entitySet.selVals().length) {
					for (int i = 0; i < entitySet.selOpts().length; i++) {
						String key = entitySet.selOpts()[i];
						String value = entitySet.selVals()[i];
						if (!StringUtils.isEmpty(key)
								&& !StringUtils.isEmpty(value)) {
							if (!StringUtils.isEmpty(opt.toString()))
								opt.append(",");
							opt.append(key + ":" + value);
						}
					}
					html.append(opt);
				}
				html.append("\">\n");
				if (entitySet.keys().length == entitySet.vals().length) {
					for (int i = 0; i < entitySet.keys().length; i++) {
						String key = entitySet.keys()[i];
						String value = entitySet.vals()[i];
						html.append(globStr + "            <option title='"
								+ key + "' value='" + value + "' ");
						if (!isquery) {
							html.append("<c:if test=\"${ " + clzName + "."
									+ name + " eq '" + value
									+ "' }\" > selected = 'selected' </c:if>");
						}
						html.append(">" + key + "</option>\n");
					}
				}
				html.append(globStr + "        </select>\n");
			}
		} else if ("text".equals(entitySet.inputType())) {
			html.append(globStr + "        <input style=\"" + width
					+ "\" type='" + entitySet.inputType() + "' name='"
					+ clzName + "." + name + "' id='" + name
					+ "' class='easyui-" + entitySet.css() + "'");
			// easyui的参数
			StringBuffer opt = new StringBuffer();
			if (entitySet.selOpts().length == entitySet.selVals().length) {
				html.append(" data-options=\"");
				for (int i = 0; i < entitySet.selOpts().length; i++) {
					String key = entitySet.selOpts()[i];
					String value = entitySet.selVals()[i];
					if (isquery && "required".equals(key.trim()))
						continue;
					if (isquery && "missingMessage".equals(key.trim()))
						continue;
					if (isquery && "invalidMessage".equals(key.trim()))
						continue;
					if (isquery && "validType".equals(key.trim()))
						continue;
					if (!StringUtils.isEmpty(key)
							&& !StringUtils.isEmpty(value)) {
						if (!StringUtils.isEmpty(opt.toString()))
							opt.append(",");
						opt.append(key + ":\'" + value + "\'");
					}
				}
				html.append(opt);
				html.append("\"");
			}
			if (!isquery)
				html.append(" value=\"${" + clzName + "." + name + "}\"");
			html.append(" />\n");
		} else if ("textarea".equals(entitySet.inputType())) {
			html.append(globStr + "        <textarea rows='5' style=\"" + width
					+ "\" " + " name='" + clzName + "." + name + "' id='"
					+ name + "'>${" + clzName + "." + name + "}</textarea>\n");
		} else if ("password".equals(entitySet.inputType())) {
			html.append(globStr + "        <input style=\"" + width
					+ "\" type='" + entitySet.inputType() + "' name='"
					+ clzName + "." + name + "' id='" + name + "' />\n");
		} else {
			html.append(globStr + "        <input style=\"" + width
					+ "\" type='" + entitySet.inputType() + "' name='"
					+ clzName + "." + name + "' id='" + name + "' value='${"
					+ clzName + "." + name + "}'/>\n");
		}
		return html;
	}
}
